/*
 * $Id: ResourcesTableHelper.java 28 2013-05-21 12:11:22Z antonyhands@gmail.com $
 */
package ru.olympus.antonyhands.ao.ui.helper;

import java.util.List;

import ru.olympus.antonyhands.ao.UIHelper;
import ru.olympus.antonyhands.ao.data.AOData;
import ru.olympus.antonyhands.ao.data.entities.AOItem;
import ru.olympus.antonyhands.ao.data.util.ByTitleComparator;
import ru.olympus.antonyhands.ao.util.GoogleIterable;
import ru.olympus.antonyhands.ao.util.StringUtilities;

import com.vaadin.ui.Button;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Table;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;

/**
 * @author AntonyHands
 * @since 21.05.2013
 */
public class ResourcesTableHelper
{

    public static Table createResourcesTable()
    {
        Table _resources = new Table("Ресурсы");
        _resources.setPageLength(0);
        _resources.addContainerProperty("item", ComboBox.class, null);
        _resources.addContainerProperty("quantity", Long.class, null);
        _resources.addContainerProperty("delButton", Button.class, null);
        _resources.setColumnHeader("item", "Предмет");
        _resources.setColumnHeader("quantity", "Количество");
        _resources.setColumnHeader("delButton", "");
        _resources.setEditable(true);
        return _resources;
    }
    
    public static void addRowToResourcesTable(final Table _resources, final Object newRowId,
            String itemCode, Long quantity)
    {
        ComboBox itemBox = new ComboBox();
        itemBox.setNullSelectionAllowed(false);
        List<AOItem> list = GoogleIterable.with(AOData.getInstance().listItems())
                .sort(new ByTitleComparator()).toArrayList();
        UIHelper.refillSelect(itemBox, list);
        if (list.size() > 0)
            itemBox.setValue(StringUtilities.isEmpty(itemCode) ? list.get(0).getCode() : itemCode);
        Button delButton = new Button("Удалить");
        delButton.addListener(new ClickListener()
        {
            private static final long serialVersionUID = 6016282560688968264L;

            private final Object resId = newRowId;

            @Override
            public void buttonClick(ClickEvent event)
            {
                _resources.removeItem(resId);
            }
        });
        _resources.addItem(new Object[]{ itemBox, quantity, delButton }, newRowId);
    }
}
